package net.xxcl.kygl.interceptor;

import net.xxcl.kygl.mapper.ActionMapper;
import net.xxcl.kygl.pojo.Action;
import net.xxcl.kygl.pojo.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

/**
 * User: 夏汛
 * Date: 12-1-18
 * Time: 下午10:17
 */
@Service
public class AuthInterceptor implements HandlerInterceptor{

    @Autowired
    private ActionMapper actionMapper;

    private boolean isAjax(HttpServletRequest request,HttpServletResponse response) throws Exception{
        if(request.getHeader("x-requested-with")!=null
                && request.getHeader("x-requested-with").equalsIgnoreCase("Ext.basex")){
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String requestURI = request.getRequestURI();
        //如果是登录请求不继续验证权限
        if(requestURI.equals("/user/login.do")){
            return true;
        }
        if(request.getSession().getAttribute("user")==null){
            response.setHeader("sessionstatus","timeout");
            PrintWriter writer = response.getWriter();
            writer.print("{'sessionstatus':'timeout'}");
            writer.flush();
            writer.close();
            return false;
        } else {
            List<Integer> roles = (List<Integer>)request.getSession().getAttribute("roles");
            Criteria criteria = new Criteria();
            criteria.put("roles",roles);
            criteria.put("action",requestURI);
            List<Action> actions = actionMapper.userAuthUrl(criteria);
//            if(actions.size()>0){
//                return true;
//            } else {
//                response.setHeader("sessionstatus","timeout");
//                return false;
//            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }
}
